import fs from 'fs';
import fetch from "node-fetch"

const filepath = 'data/musickey'
const num = 30 // 刷取30遍，最高412
const mid = '0002CjRy1DqBCk' // 音乐ID，如何获取音乐ID教程：https://gitee.com/Tloml-Starry/Plugin-Example/raw/master/PICTRUE/QQ音乐ID获取.png

fs.mkdirSync(filepath, { recursive: true });
export class example extends plugin {
    constructor() {
        super({
            name: '听歌时长',
            dsc: 'example',
            event: 'message',
            priority: 5000,
            rule: [
                {
                    reg: /^(#|\/)?查询听歌时长$/,
                    fnc: 'inquire'
                },
                {
                    reg: /^(#|\/)?刷听歌时长$/,
                    fnc: 'Get_Time'
                },
                {
                    reg: /^#Q音登录$/,
                    fnc: 'GET_Cookie'
                },
                {
                    reg: /^over$/,
                    fnc: 'Get_musickey'
                },
                {
                    reg: /^(#|\/)?清理getQR$/,
                    fnc: 'Cleaning'
                }
            ]
        })
    }
    async inquire(e) { e.reply('请扫码查看'); return e.reply([segment.image('https://gitee.com/Tloml-Starry/Plugin-Example/raw/master/PICTRUE/听歌排行榜.png')]) }
    async Get_Time(e) {
        const user_id = e.user_id
        const user_file = `${filepath}/${user_id}.json`
        if (!fs.existsSync(user_file)) { return e.reply('请先发送#Q音登录，登录验证后再发送#刷听歌时长') }
        const READ = fs.readFileSync(user_file, 'utf8')
        const DATA = JSON.parse(READ)
        const FETCH_URL_DATA = await fetch(`https://oiapi.net/API/QQMusic_RunTime/?uin=${DATA['data']['musicid']}&id=${mid}&num=${num}&authst=${DATA['data']['musickey']}`)
        const PARSING_DATA = await FETCH_URL_DATA.json()
        const URL_CODE = PARSING_DATA['code']
        const URL_MESSAGE = PARSING_DATA['message']
        if (DATA['data']['errtip']) {
            return e.reply([DATA['data']['errTip2'] + '\n' + DATA['data']['errtip']])
        }
        if (URL_CODE === -1 || URL_CODE === -2 || URL_CODE === -3 || URL_CODE === -4) {
            return e.reply(URL_MESSAGE)
        } else if (URL_CODE === 1) {
            return e.reply([segment.at(user_id), `\n刷取成功！\n刷取了：${num}遍\n刷取账号：${DATA['data']['str_musicid']}\n刷取时长：${URL_MESSAGE}\n刷取音乐：\nhttps://y.qq.com/n/ryqq/songDetail/${mid}\n排行榜查看可能会有延迟\n未成功请重新发送#Q音登录`])
        }
    }
    async GET_Cookie(e) {
        const user_id = e.user_id
        const FETCH_URL_DATA = await fetch('https://oiapi.net/API/QQ_Cookie/?format=y.qq.com&step=getQR')
        const PARSING_DATA = await FETCH_URL_DATA.json()
        fs.writeFileSync(`${filepath}/getQR${user_id}.json`, JSON.stringify(PARSING_DATA, null, 4), 'utf8')
        if (PARSING_DATA['code'] === 1) {
            e.reply([segment.at(user_id), '\n请于两分钟内扫码登录\n登录完成之后发送：over', segment.image(PARSING_DATA['data']['url'])])
        } else {
            return e.reply('接口返回错误，请检查接口\ncode: ' + PARSING_DATA['code'])
        }
    }

    async Get_musickey(e) {
        const user_id = e.user_id
        const READ = fs.readFileSync(`${filepath}/getQR${user_id}.json`, 'utf8')
        const DATA = JSON.parse(READ)
        const FETCH_URL_DATA = await fetch(`https://oiapi.net/API/QQ_Cookie/?format=y.qq.com&step=verifyQR&qrsig=${DATA['data']['qrsig']}`)
        const PARSING_DATA = await FETCH_URL_DATA.json()
        const URL_CODE = PARSING_DATA['code']
        if (URL_CODE === -3 || URL_CODE === -2 || URL_CODE === -6 || URL_CODE === -4) {
            return e.reply(PARSING_DATA['message'])
        } else if (URL_CODE === 1) {
            fs.writeFileSync(`${filepath}/${user_id}.json`, JSON.stringify(PARSING_DATA, null, 4), 'utf8')
            return e.reply('登录成功！')
        }
    }
    async Cleaning(e) {
        if (!e.isMaster) return
        fs.readdir(filepath, (err, files) => {
            if (err) {
                logger.error(err);
                return;
            }

            files.forEach((file) => {
                if (file.startsWith('getQR')) {
                    fs.unlink(`${filepath}/${file}`, (err) => {
                        if (err) {
                            logger.error(err);
                            return;
                        }
                        logger.mark(`${file} 已成功删除`);
                    });
                }
            });
            return e.reply('清理完成')
        });
    }
}